package com.chase.passwordmaster.pass

import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.chase.passwordmaster.R
import com.chase.passwordmaster.config.SP_KEY_SETTING_PURE_PASS_BACKGROUND
import com.chase.passwordmaster.data.GlobalData
import com.chase.passwordmaster.data.initGlobalData
import com.chase.passwordmaster.main.MainActivity
import com.chase.passwordmaster.utils.*
import requireWriteAndReadPermission

class PassActivity : AppCompatActivity() {

    private lateinit var cpInputPass: EditText
    private lateinit var cpPass: ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_pass)

        initGlobalData()

        initLogger()

        cpInputPass = findViewById(R.id.input_pass_pass)
        cpPass = findViewById(R.id.pass_pass)

        if (GlobalData.encryptedLoginPasswordObject == null) {
            // 为空，设置 loginPassword
            // 跳转到 SetPassActivity
            SetPassActivity.actionStart(this)
            this.finish()
        }

        useImmersingNavigator(lightStatusBar = false)

        initPurePassBG()
        initCPPass()
        initCPInputPass()
    }

    override fun onResume() {
        Log.d("GSC:", "onResume")
        super.onResume()
        if (GlobalData.encryptedLoginPasswordObject == null) {
            // 为空，设置 loginPassword
            // 跳转到 SetPassActivity
            SetPassActivity.actionStart(this)
            this.finish()
        }
    }

    private fun initLogger() {
        requireWriteAndReadPermission(this)

        Logger.initialize(config = Logger.LoggerConfig(
            // dir = Environment.getExternalStorageDirectory().absolutePath,
            dir = getExternalFilesDir(null).absolutePath + "/log",
            logName = "log.txt"
        ))
    }

    private fun initPurePassBG() {
        if (SPUtils(this, "pmConfigs").getBoolean(SP_KEY_SETTING_PURE_PASS_BACKGROUND, false)) {
            findViewById<View>(R.id.pure_bg_pass).visibility = View.VISIBLE
            findViewById<View>(R.id.pic_bg_pass).visibility = View.GONE

            useDarkStatusBar()
        }
    }

    private fun initCPPass() {
        cpPass.setOnClickListener {
            validatePassAndJump()
        }
    }

    private fun initCPInputPass() {
        cpInputPass.setOnEditorActionListener { v, actionId, event ->
            if (EditorInfo.IME_ACTION_GO == actionId) {
                validatePassAndJump()
                return@setOnEditorActionListener true
            }
            false
        }
    }

    /**
     * Validate pass and jump to next page if right
     */
    private fun validatePassAndJump() {
        // Get pass
        val pass = cpInputPass.text.toString()
        if (pass.isNotBlank()) {
            GlobalData.encryptedLoginPasswordObject
                ?.let {
                    if (BCrypt.checkpw(pass, it.encodedLoginPassword)) {
                        // Right
                        // Set global data
                        GlobalData.loginPassword = pass

                        // Jump
                        MainActivity.actionStart(this, pass)
                        this.finish()
                    } else {
                        // wrong
                        showToast("密码错误")
                    }
                }
                ?: showToast("尚未设置进入密码，尝试清除软件数据后重新设置（数据会丢失）")
        } else {
            showToast("密码不能为空")
        }
    }
}